package com.spd.shop.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spd.shop.common.Constants;
import com.spd.shop.common.Result;
import com.spd.shop.controller.dto.AdminDTO;
import com.spd.shop.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.spd.shop.service.IAdminService;
import com.spd.shop.entity.Admin;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 孙沛栋
 * @since 2023-03-14
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private IAdminService adminService;

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody AdminDTO adminDTO) {
        String username = adminDTO.getUsername();
        String password = adminDTO.getPassword();
        if (StringUtils.isBlank(username)||StringUtils.isBlank(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }

        AdminDTO dto = adminService.login(adminDTO);
        return Result.success(dto);
    }


    //新增或者更新
    @PostMapping
    public boolean save(@RequestBody Admin admin) {
        return adminService.saveOrUpdate(admin);
    }

    //删除
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id) {
        return adminService.removeById(id);
    }

    //批量删除
    @PostMapping("/del/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids) {
        return adminService.removeBatchByIds(ids);
    }

    //查询所有数据
    @GetMapping
    public List<Admin> findAll() {
        return adminService.list();
    }
    //根据id查询
    @GetMapping("/{id}")
    public Admin findOne(@PathVariable Integer id) {
        return adminService.getById(id);
    }
    //分页查询
    @GetMapping("/page")
    public Page<Admin> findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String username,
                                @RequestParam(defaultValue = "") String name,
                                @RequestParam(defaultValue = "") String phone) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(username)) {
            queryWrapper.like("username", username);
        }
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        if (!"".equals(phone)) {
            queryWrapper.like("phone", phone);

        }
/*//获取当前用户信息
        Admin currentAdmin = TokenUtils.getCurrentAdmin();
        System.out.println(currentAdmin.getName());*/
        return adminService.page(new Page<>(pageNum, pageSize),queryWrapper);
    }




}

